package com.yanqu.road.dao.impl.cross.orewar;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.crossorewar.CrossOrePitInfo;
import com.yanqu.road.entity.crossorewar.CrossOreWarNotice;
import com.yanqu.road.entity.crossorewar.CrossOreWarRecord;
import com.yanqu.road.entity.crossorewar.CrossUserOrePit;
import com.yanqu.road.entity.player.UserBaseInfo;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossOreWarDaoImpl extends TempDao {

    public boolean updateCrossUserOrePitList(List<CrossUserOrePit> userOrePitList) {
        boolean result = false;
        String sql = "UPDATE t_c_activity_orewar SET stationId=?,userId=?,serverId=?,nickName=?,patronsInfoStr=?,joinTime=?,lastGetRewardTime=?," +
                "isBlowout=?,userBaseInfo=?,beautySkillAddition=?,patronsSkillAddition=?,updateIndex=? WHERE "
                + "activityId=? and pitId=? and groupId=?";
        getDb().setConnName(DbNameStrategy.getCrossDb());
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (CrossUserOrePit orePit : userOrePitList) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.INTEGER, orePit.getStationId()));
            para.put(i++, new DbParameter(Types.BIGINT, orePit.getUserId()));
            para.put(i++, new DbParameter(Types.BIGINT, orePit.getServerId()));
            para.put(i++, new DbParameter(Types.VARCHAR, orePit.getNickName()));
            para.put(i++, new DbParameter(Types.VARCHAR, orePit.getPatronsInfoStr()));
            para.put(i++, new DbParameter(Types.BIGINT, orePit.getJoinTime()));
            para.put(i++, new DbParameter(Types.BIGINT, orePit.getLastGetRewardTime()));
            para.put(i++, new DbParameter(Types.BOOLEAN, orePit.isBlowout()));
            para.put(i++, new DbParameter(Types.VARCHAR, orePit.getUserBaseInfoJsonStr()));
            para.put(i++, new DbParameter(Types.INTEGER, orePit.getBeautySkillAddition()));
            para.put(i++, new DbParameter(Types.INTEGER, orePit.getPatronsSkillAddition()));
            para.put(i++, new DbParameter(Types.BIGINT, 0L));
            para.put(i++, new DbParameter(Types.INTEGER, orePit.getActivityId()));
            para.put(i++, new DbParameter(Types.INTEGER, orePit.getPitId()));
            para.put(i++, new DbParameter(Types.INTEGER, orePit.getGroupId()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }


    public long getMaxUpdateIndex(int activityId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT max(updateIndex) as updateIndex FROM t_c_activity_orewar WHERE activityId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++,activityId);
            rs = call.executeQuery();
            while (rs.next()) {
                return rs.getLong("updateIndex");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return 0;
    }

    public Map<Integer, CrossUserOrePit> getCrossUserOrePitMap(int activityId,int groupId) {
        Map<Integer, CrossUserOrePit> dataMap = new ConcurrentHashMap<>();
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "SELECT * FROM t_c_activity_orewar WHERE activityId = ? AND groupId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++,activityId);
            call.setInt(i++,groupId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUserOrePit data = initCrossUserOrePit(rs);
                dataMap.put(data.getPitId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    //跨服的玩家坑位信息
    private CrossUserOrePit initCrossUserOrePit(ResultSet rs) throws SQLException {
        CrossUserOrePit data = new CrossUserOrePit();
        data.setActivityId(rs.getInt("activityId"));
        data.setGroupId(rs.getInt("groupId"));
        data.setPitId(rs.getInt("pitId"));
        data.setStationId(rs.getInt("stationId"));
        data.setUserId(rs.getLong("userId"));
        data.setServerId(rs.getLong("serverId"));
        data.setNickName(rs.getString("nickName"));
        data.setPatronsInfoStr(rs.getString("patronsInfoStr"));
        data.setJoinTime(rs.getLong("joinTime"));
        data.setLastGetRewardTime(rs.getLong("lastGetRewardTime"));
        data.setBlowout(rs.getBoolean("isBlowout"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setUserBaseInfo(userBaseInfo);
        }
        return data;
    }

    public boolean initCrossUserOrePitMap(Map<Integer, CrossOrePitInfo> crossOrePitInfoMap, Map<Integer, CrossUserOrePit> crossUserOrePitMap,int groupId) {
        boolean result = false;
        String sql = "INSERT INTO t_c_activity_orewar(activityId,pitId,stationId,userId,serverId,nickName,patronsInfoStr,joinTime," +
                "lastGetRewardTime,isBlowout,userBaseInfo,beautySkillAddition,patronsSkillAddition,updateIndex,groupId)"
                + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        getDb().setConnName(DbNameStrategy.getCrossDb());
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (CrossOrePitInfo pitInfo : crossOrePitInfoMap.values()) {
            if (!crossUserOrePitMap.containsKey(pitInfo.getPitId())) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.INTEGER, pitInfo.getActivityId()));
                para.put(i++, new DbParameter(Types.INTEGER, pitInfo.getPitId()));
                para.put(i++, new DbParameter(Types.INTEGER, pitInfo.getStationId()));
                para.put(i++, new DbParameter(Types.BIGINT, 0L));
                para.put(i++, new DbParameter(Types.BIGINT, 0L));
                para.put(i++, new DbParameter(Types.VARCHAR, ""));
                para.put(i++, new DbParameter(Types.VARCHAR, "[]"));
                para.put(i++, new DbParameter(Types.BIGINT, 0L));
                para.put(i++, new DbParameter(Types.BIGINT, 0L));
                para.put(i++, new DbParameter(Types.BOOLEAN, false));
                para.put(i++, new DbParameter(Types.VARCHAR, "{}"));
                para.put(i++, new DbParameter(Types.INTEGER, 0));
                para.put(i++, new DbParameter(Types.INTEGER, 0));
                para.put(i++, new DbParameter(Types.BIGINT, 0L));
                para.put(i++, new DbParameter(Types.INTEGER, groupId));
                mapList.add(para);
            }
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }


    public Map<Long, Map<Long, List<CrossOreWarRecord>>> getCrossOreWarRecordMap(int activityId,int groupId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, Map<Long, List<CrossOreWarRecord>>> dataMap = new ConcurrentHashMap<>();
        String sql = "SELECT * FROM t_c_activity_orewar_record where activityId = ? and groupId = ? order by recordTime desc";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, groupId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossOreWarRecord data = initCrossOreWarRecord(rs);
                if(!dataMap.containsKey(data.getServerId())){
                    dataMap.put(data.getServerId(), new ConcurrentHashMap<>());
                }
                if(!dataMap.get(data.getServerId()).containsKey(data.getUserId())){
                    dataMap.get(data.getServerId()).put(data.getUserId(), new ArrayList<>());
                }
                dataMap.get(data.getServerId()).get(data.getUserId()).add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public Map<Long, List<CrossOreWarRecord>> getCrossOreWarRecordMapServer(int activityId,long serverId) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, List<CrossOreWarRecord>> dataMap = new ConcurrentHashMap<>();
        String sql = "SELECT * FROM t_c_activity_orewar_record where activityId = ? AND serverId = ? order by recordTime desc";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setLong(2, serverId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossOreWarRecord data = initCrossOreWarRecord(rs);
                if(!dataMap.containsKey(data.getUserId())){
                    dataMap.put(data.getUserId(), new ArrayList<>());
                }
                dataMap.get(data.getUserId()).add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    private CrossOreWarRecord initCrossOreWarRecord(ResultSet rs) throws SQLException {
        CrossOreWarRecord data = new CrossOreWarRecord();
        data.setRecordUid(rs.getString("recordUid"));
        data.setUserId(rs.getLong("userId"));
        data.setServerId(rs.getLong("serverId"));
        data.setActivityId(rs.getInt("activityId"));
        data.setPitId(rs.getInt("pitId"));
        data.setEnemyUserId(rs.getLong("enemyUserId"));
        String baseUserInfoStr = rs.getString("enemyBaseData");
        data.setGroupId(rs.getInt("groupId"));
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setEnemyBaseData(userBaseInfo);
        }
        data.setRecordTime(rs.getLong("recordTime"));
        data.setWin(rs.getBoolean("isWin"));
        return data;
    }

    public boolean addCrossOreWarRecordList(List<CrossOreWarRecord> crossOreWarRecordList) {
        boolean result = false;
        getDb().setConnName(DbNameStrategy.getCrossDb());
        String sql = "INSERT INTO t_c_activity_orewar_record(recordUid,userId,serverId,activityId,groupId,pitId,enemyUserId,enemyBaseData,recordTime,isWin) VALUES(?,?,?,?,?,?,?,?,?,?)";
        List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
        for (CrossOreWarRecord info : crossOreWarRecordList) {
            Map<Integer, DbParameter> para = new HashMap<>();
            int i = 1;
            para.put(i++, new DbParameter(Types.VARCHAR, info.getRecordUid()));
            para.put(i++, new DbParameter(Types.BIGINT, info.getUserId()));
            para.put(i++, new DbParameter(Types.BIGINT, info.getServerId()));
            para.put(i++, new DbParameter(Types.INTEGER, info.getActivityId()));
            para.put(i++, new DbParameter(Types.INTEGER, info.getGroupId()));
            para.put(i++, new DbParameter(Types.INTEGER, info.getPitId()));
            para.put(i++, new DbParameter(Types.BIGINT, info.getEnemyUserId()));
            para.put(i++, new DbParameter(Types.VARCHAR, info.getEnemyBaseDataJsonStr()));
            para.put(i++, new DbParameter(Types.BIGINT, info.getRecordTime()));
            para.put(i++, new DbParameter(Types.BOOLEAN, info.isWin()));
            mapList.add(para);
        }
        if (getDb().executeBatchQuery(sql, mapList) > -1) {
            result = true;
        }
        return result;
    }




    /*=====================================notice=======================================================*/
    public LinkedList<CrossOreWarNotice> getCrossOreWarNoticeList(int activityId, int groupId,int maxCount) {
        String sql = "select * from t_c_activity_orewar_notice where activityId = ? and groupId = ? order by noticeTime desc limit ?";
        ResultSet rs = null;
        CallableStatement call = null;
        LinkedList<CrossOreWarNotice> dataList = new LinkedList<>();
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, groupId);
            call.setInt(3, maxCount);
            rs = call.executeQuery();
            while (rs.next()) {
                dataList.addFirst(initCrossOreWarNotice(rs));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public boolean addCrossOreWarNoticeList(List<CrossOreWarNotice> noticeList) {
        String sql = "INSERT INTO t_c_activity_orewar_notice(noticeUid,activityId,groupId,pitId,noticeTime,userId,serverId,userBaseInfo,enemyUserId,enemyBaseInfo) " +
                " VALUES(?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            boolean result = false;
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            for (CrossOreWarNotice notice : noticeList) {
                Map<Integer, DbParameter> para = new HashMap<>();
                int i = 1;
                para.put(i++, new DbParameter(Types.NVARCHAR, notice.getNoticeUid()));
                para.put(i++, new DbParameter(Types.INTEGER, notice.getActivityId()));
                para.put(i++, new DbParameter(Types.INTEGER, notice.getGroupId()));
                para.put(i++, new DbParameter(Types.INTEGER, notice.getPitId()));
                para.put(i++, new DbParameter(Types.BIGINT, notice.getNoticeTime()));
                para.put(i++, new DbParameter(Types.BIGINT, notice.getUserId()));
                para.put(i++, new DbParameter(Types.BIGINT, notice.getServerId()));
                para.put(i++, new DbParameter(Types.NVARCHAR, notice.getUserBaseInfoJsonStr()));
                para.put(i++, new DbParameter(Types.BIGINT, notice.getEnemyUserId()));
                para.put(i++, new DbParameter(Types.NVARCHAR, notice.getEnemyBaseInfoJsonStr()));
                mapList.add(para);
            }

            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                result = true;
            }
            return result;
        }catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    private CrossOreWarNotice initCrossOreWarNotice(ResultSet rs) throws SQLException {
        CrossOreWarNotice data = new CrossOreWarNotice();
        data.setNoticeUid(rs.getString("noticeUid"));
        data.setActivityId(rs.getInt("activityId"));
        data.setPitId(rs.getInt("pitId"));
        data.setNoticeTime(rs.getLong("noticeTime"));
        data.setUserId(rs.getLong("userId"));
        data.setServerId(rs.getLong("serverId"));
        data.setGroupId(rs.getInt("groupId"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setUserBaseInfo(userBaseInfo);
        }
        data.setEnemyUserId(rs.getLong("enemyUserId"));
        baseUserInfoStr = rs.getString("enemyBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setEnemyBaseInfo(userBaseInfo);
        }
        return data;
    }
}
